
import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import axios from "axios";
import {
  Card,
  Typography,
  Tag,
  Avatar,
  Button,
  Divider,
  List,
  Space,
  Modal,
  Form,
  Input,
  Popconfirm,
  Spin,
  message,
  InputNumber,
  Alert,
  Upload
} from "antd";
import {
  UserOutlined,
  GiftOutlined,
  ClockCircleOutlined,
  CheckOutlined,
  CloseOutlined,
  WarningOutlined,
  DeleteOutlined,
  UploadOutlined
} from "@ant-design/icons";
import dayjs from "dayjs";
import { getAuthToken } from "@/router/index.jsx";
import "./style.styl";

const { Title, Paragraph } = Typography;
const { TextArea } = Input;

// 创建axios实例
const api = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 10000,
});

// 设置请求拦截器
api.interceptors.request.use(config => {
  config.headers.Authorization = `${getAuthToken()}`;
  return config;
});

// 设置响应拦截器
api.interceptors.response.use(
    response => response,
    error => {
      if (error.response) {
        const { status, data } = error.response;
        if (status === 401) {
          localStorage.removeItem("access_token");
          window.location.href = "/login?redirect=" + encodeURIComponent(window.location.pathname);
        }
        return Promise.reject({
          code: data.code || status,
          message: data.message || "请求失败"
        });
      }
      return Promise.reject({
        code: -1,
        message: "网络错误，请检查网络连接"
      });
    }
);

const BountyDetailContent = () => {
  const { taskId } = useParams();
  const navigate = useNavigate();
  const [task, setTask] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [completeModalVisible, setCompleteModalVisible] = useState(false);
  const [resourceId, setResourceId] = useState(null);
  const [error, setError] = useState(null);
  const [form] = Form.useForm();

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      const response = await api.get("/api/user/info");
      setCurrentUser(response.data.data);
    } catch (error) {
      console.error("获取用户信息失败:", error);
      message.error(error.message || "获取用户信息失败");
      setError(error);
    }
  };

  // 获取悬赏任务详情
  const fetchBountyTask = async (id) => {
    if (!id || isNaN(id)) {
      setError({ message: "无效的任务ID" });
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const response = await api.get(`/api/bounty-tasks/${id}`);
      setTask(response.data.data);
      setError(null);
    } catch (err) {
      console.error("获取悬赏详情失败:", err);
      message.error(err.message || "获取悬赏任务详情失败");
      setError(err);
    } finally {
      setLoading(false);
    }
  };

  // 完成悬赏任务
  const completeBounty = async () => {
    if (!taskId || isNaN(taskId)) {
      message.error("无效的任务ID");
      return;
    }

    if (!resourceId || resourceId <= 0) {
      message.error("请输入有效的资源ID");
      return;
    }

    setSubmitting(true);
    try {
      await api.post(`/api/bounty-tasks/${taskId}/complete`, null, {
        params: {
          resourceId: resourceId
        }
      });
      message.success("悬赏任务提交成功，等待发布者确认");
      setCompleteModalVisible(false);
      setResourceId(null);
      fetchBountyTask(taskId);
    } catch (err) {
      console.error("提交悬赏任务失败:", err);
      if (err.code === 403) {
        message.error("无权限执行此操作");
      } else if (err.code === 1008) {
        message.error("此资源已被他人提交");
      } else {
        message.error(err.message || "提交失败，请稍后重试");
      }
    } finally {
      setSubmitting(false);
    }
  };

  // 关闭悬赏任务
  const closeBounty = async () => {
    if (!taskId || isNaN(taskId)) {
      message.error("无效的任务ID");
      return;
    }

    setSubmitting(true);
    try {
      await api.post(`/api/bounty-tasks/${taskId}/close`);
      message.success("悬赏任务已关闭");
      fetchBountyTask(taskId);
    } catch (err) {
      console.error("关闭悬赏任务失败:", err);
      if (err.code === 403) {
        message.error("无权限执行此操作");
      } else if (err.code === 1007) {
        message.error("悬赏任务已超时无法关闭");
      } else {
        message.error(err.message || "关闭失败，请稍后重试");
      }
    } finally {
      setSubmitting(false);
    }
  };

  // 删除悬赏任务
  const deleteBounty = async () => {
    if (!taskId || isNaN(taskId)) {
      message.error("无效的任务ID");
      return;
    }

    setSubmitting(true);
    try {
      await api.delete(`/api/bounty-tasks/${taskId}`);
      message.success("悬赏任务已删除");
      navigate("/community/bounty");
    } catch (err) {
      console.error("删除悬赏任务失败:", err);
      if (err.code === 403) {
        message.error("无权限执行此操作");
      } else {
        message.error(err.message || "删除失败，请稍后重试");
      }
    } finally {
      setSubmitting(false);
    }
  };

  useEffect(() => {
    if (taskId) {
      fetchBountyTask(taskId);
    } else {
      setError({ message: "任务ID未提供" });
      setLoading(false);
    }

    fetchCurrentUser();
  }, [taskId]);

  const getStatusColor = (status) => {
    switch (status) {
      case "active": return "green";
      case "completed": return "blue";
      case "expired": return "orange";
      case "closed": return "gray";
      default: return "default";
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case "active": return "进行中";
      case "completed": return "已完成";
      case "expired": return "已过期";
      case "closed": return "已关闭";
      default: return "未知状态";
    }
  };

  const isPublisher = () => {
    return currentUser && task && task.publisherId === currentUser.id;
  };

  const isCompleter = () => {
    return currentUser && task && task.completedById === currentUser.id;
  };

  const canClose = () => {
    return task && (task.status === "active" || task.status === "expired");
  };

  const canComplete = () => {
    return currentUser && task &&
        task.status === "active" &&
        !isPublisher();
  };

  const isExpired = () => {
    return task && task.deadline && dayjs(task.deadline).isBefore(dayjs());
  };

  const navigateToResource = () => {
    if (task?.resourceId) {
      navigate(`/resource/${task.resourceId}`);
    }
  };

  if (!taskId) {
    return (
        <div className="error-container">
          <Card>
            <Alert
                message="任务ID未提供"
                description="您访问的悬赏任务不存在或链接无效"
                type="error"
                showIcon
            />
            <div style={{ marginTop: 16 }}>
              <Button type="primary" onClick={() => navigate("/community/bounty")}>
                返回悬赏列表
              </Button>
            </div>
          </Card>
        </div>
    );
  }

  if (loading) {
    return (
        <div className="loading-container">
          <Spin size="large" tip="加载悬赏任务详情..." />
        </div>
    );
  }

  if (error || !task) {
    return (
        <div className="error-container">
          <Card>
            <Alert
                message="加载失败"
                description={error?.message || "悬赏任务不存在或加载失败"}
                type="error"
                showIcon
            />
            <div style={{ marginTop: 16 }}>
              <Button type="primary" onClick={() => navigate("/community/bounty")}>
                返回悬赏列表
              </Button>
            </div>
          </Card>
        </div>
    );
  }

  return (
      <div className="bounty-detail-container">
        <Card className="bounty-detail-card">
          <div className="bounty-header">
            <div className="bounty-title-section">
              <Title level={3}>{task.title}</Title>
              <Space>
                <Tag color={getStatusColor(task.status)}>
                  {task.status === "active" && isExpired()
                      ? "已过期"
                      : getStatusText(task.status)}
                </Tag>
                <Tag icon={<GiftOutlined />} color="purple">
                  奖励: {task.rewardMagic} 魔力值
                </Tag>
              </Space>
            </div>

            <div className="bounty-actions">
              {isPublisher() && canClose() && (
                  <Popconfirm
                      title="确定要关闭此悬赏任务吗？关闭后将返还魔力值"
                      onConfirm={closeBounty}
                      okText="确认"
                      cancelText="取消"
                      disabled={submitting}
                  >
                    <Button
                        icon={<CloseOutlined />}
                        loading={submitting}
                        style={{ marginRight: 8 }}
                    >
                      关闭悬赏
                    </Button>
                  </Popconfirm>
              )}

              {isPublisher() && canClose() && (
                  <Popconfirm
                      title="确定要删除此悬赏任务吗？"
                      onConfirm={deleteBounty}
                      okText="确定"
                      cancelText="取消"
                  >
                    <Button danger icon={<DeleteOutlined />} loading={submitting}>
                      删除任务
                    </Button>
                  </Popconfirm>
              )}

              {canComplete() && (
                  <Button
                      type="primary"
                      icon={<CheckOutlined />}
                      onClick={() => setCompleteModalVisible(true)}
                  >
                    完成悬赏
                  </Button>
              )}
            </div>
          </div>

          <div className="publisher-info">
            <Avatar size="small" icon={<UserOutlined />} />
            <span className="publisher-name">
            {task.publisherName || "未知用户"}
          </span>
            <span className="publish-time">
            <ClockCircleOutlined /> 发布于{" "}
              {dayjs(task.createdAt).format("YYYY-MM-DD HH:mm")}
          </span>
          </div>

          <Divider orientation="left">需求描述</Divider>
          <div className="bounty-description">
            <Paragraph>{task.description}</Paragraph>
          </div>

          <Divider orientation="left">悬赏详情</Divider>
          <div className="bounty-meta-info">
            <div className="info-item">
              <span className="info-label">截止时间：</span>
              <span>
              {task.deadline ? dayjs(task.deadline).format("YYYY-MM-DD HH:mm") : "无限制"}
                {task.status === "active" && isExpired() && (
                    <Tag color="orange" style={{ marginLeft: 8 }}>已过期</Tag>
                )}
            </span>
            </div>

            {task.completedByName && (
                <div className="info-item">
                  <span className="info-label">完成者：</span>
                  <span>{task.completedByName}</span>
                </div>
            )}

            {task.completedAt && (
                <div className="info-item">
                  <span className="info-label">完成时间：</span>
                  <span>{dayjs(task.completedAt).format("YYYY-MM-DD HH:mm")}</span>
                </div>
            )}

            {task.resourceName && (
                <div className="info-item">
                  <span className="info-label">完成资源：</span>
                  <Button
                      type="link"
                      onClick={navigateToResource}
                      style={{ padding: 0 }}
                  >
                    {task.resourceName}
                  </Button>
                </div>
            )}
          </div>

          {task.status === "expired" && !task.completedById && (
              <Alert
                  message="悬赏已过期"
                  description="此悬赏任务已经超过截止日期，您无法完成此任务。"
                  type="warning"
                  showIcon
                  style={{ marginTop: 16 }}
              />
          )}

          {currentUser && isCompleter() && !isPublisher() && task.status === "completed" && (
              <Alert
                  message="恭喜您完成了该悬赏任务！"
                  description={`您已成功获得 ${task.rewardMagic} 魔力值奖励。`}
                  type="success"
                  showIcon
                  style={{ marginTop: 16 }}
              />
          )}

          {currentUser && isPublisher() && task.status === "completed" && (
              <Alert
                  message="悬赏完成通知"
                  description="您的悬赏任务已被用户完成，感谢您为社区做出的贡献！"
                  type="success"
                  showIcon
                  style={{ marginTop: 16 }}
              />
          )}
        </Card>

        {!currentUser && !loading && (
            <div className="login-prompt">
              <Alert
                  message="登录提示"
                  description="请登录后进行悬赏操作"
                  type="warning"
                  showIcon
                  style={{ marginTop: 16 }}
              />
            </div>
        )}

        {/* 完成悬赏模态框 */}
        <Modal
            title="完成悬赏任务"
            visible={completeModalVisible}
            onCancel={() => setCompleteModalVisible(false)}
            footer={[
              <Button key="back" onClick={() => setCompleteModalVisible(false)}>
                取消
              </Button>,
              <Button
                  key="submit"
                  type="primary"
                  loading={submitting}
                  onClick={completeBounty}
                  disabled={!resourceId || resourceId <= 0}
              >
                提交完成
              </Button>
            ]}
            width={600}
            destroyOnClose
        >
          <div style={{marginBottom: 16}}>
            <p>请提供完成此悬赏任务的资源ID：</p>
            <p style={{color: 'rgba(0,0,0,0.45)'}}>（注意：提交后无法修改）</p>
          </div>

          <InputNumber
              placeholder="请输入资源ID（数字）"
              value={resourceId}
              onChange={value => setResourceId(value)}
              min={1}
              style={{ width: '100%' }}
              onPressEnter={completeBounty}
          />

          <div style={{ marginTop: 16 }}>
            <Alert
                message="提示信息"
                description="请确保您提供的资源与悬赏任务需求一致，恶意提交虚假资源可能会受到惩罚。"
                type="info"
                showIcon
            />
          </div>
        </Modal>
      </div>
  );
};

export default BountyDetailContent;